{% extends "base.html" %}

{% block title %}批处理测试 - 英语词汇量估算工具{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-10 mx-auto">
        <div class="card">
            <div class="card-header">
                <h4 class="mb-0"><i class="fas fa-tasks me-2"></i>批处理词汇测试</h4>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <h5>使用说明</h5>
                    <div class="alert alert-info">
                        <strong>格式要求:</strong> 词A，认识；词B，认识；词C，不认识；词D，不认识；....
                        <br><strong>示例:</strong> apple，认识；book，认识；cat，不认识；dog，认识；
                    </div>
                </div>
                
                <form id="batchForm">
                    <div class="mb-3">
                        <label for="wordList" class="form-label">词汇列表</label>
                        <textarea class="form-control" id="wordList" rows="10" placeholder="请输入词汇列表，格式：词A，认识；词B，认识；词C，不认识；..."></textarea>
                        <div class="form-text">支持中文逗号、英文逗号、中文分号、英文分号作为分隔符</div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="button" id="validateBtn" class="btn btn-outline-info">
                            <i class="fas fa-check me-2"></i>验证格式
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-play me-2"></i>开始批处理
                        </button>
                    </div>
                </form>
                
                <div id="validationResult" class="mt-3" style="display: none;"></div>
                
                <div id="batchResult" class="mt-4" style="display: none;">
                    <h5>批处理结果</h5>
                    <div id="resultContent"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="alertContainer"></div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    $('#validateBtn').click(function() {
        const wordList = $('#wordList').val().trim();
        if (!wordList) {
            showAlert('请输入词汇列表', 'warning');
            return;
        }
        
        // 验证格式
        $.ajax({
            url: '{{ url_for("batch_estimate") }}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                word_list: wordList,
                validate_only: true
            }),
            success: function(response) {
                if (response.success) {
                    $('#validationResult').html(`
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>${response.message}
                        </div>
                    `).show();
                } else {
                    $('#validationResult').html(`
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>${response.message}
                        </div>
                    `).show();
                }
            },
            error: function() {
                showAlert('验证失败，请稍后重试', 'danger');
            }
        });
    });
    
    $('#batchForm').on('submit', function(e) {
        e.preventDefault();
        
        const wordList = $('#wordList').val().trim();
        if (!wordList) {
            showAlert('请输入词汇列表', 'warning');
            return;
        }
        
        // 显示加载状态
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin me-2"></i>处理中...').prop('disabled', true);
        
        $.ajax({
            url: '{{ url_for("batch_estimate") }}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                word_list: wordList
            }),
            success: function(response) {
                if (response.success) {
                    displayBatchResults(response.results);
                } else {
                    showAlert(response.message, 'danger');
                }
            },
            error: function() {
                showAlert('批处理失败，请稍后重试', 'danger');
            },
            complete: function() {
                submitBtn.html(originalText).prop('disabled', false);
            }
        });
    });
    
    function displayBatchResults(results) {
        let html = '<div class="table-responsive"><table class="table table-striped">';
        html += '<thead><tr><th>批次</th><th>估算词汇量</th><th>置信度</th><th>认识数量</th><th>不认识数量</th><th>准确率</th><th>等级</th></tr></thead><tbody>';
        
        results.forEach(function(result) {
            const levelDisplay = result.level ? result.level.display : '-';
            html += `<tr>
                <td>${result.batch_id}</td>
                <td>${result.estimate.toLocaleString()}</td>
                <td>${(result.confidence * 100).toFixed(1)}%</td>
                <td>${result.known_count}</td>
                <td>${result.unknown_count}</td>
                <td>${(result.accuracy * 100).toFixed(1)}%</td>
                <td><span class="badge bg-primary">${levelDisplay}</span></td>
            </tr>`;
        });
        
        html += '</tbody></table></div>';
        
        // 计算总体统计
        const totalEstimate = results.reduce((sum, r) => sum + r.estimate, 0);
        const avgEstimate = totalEstimate / results.length;
        const avgConfidence = results.reduce((sum, r) => sum + r.confidence, 0) / results.length;
        
        html += `<div class="card mt-3">
            <div class="card-body">
                <h6>总体统计</h6>
                <div class="row">
                    <div class="col-md-3">
                        <strong>平均估算词汇量:</strong> ${avgEstimate.toLocaleString()}
                    </div>
                    <div class="col-md-3">
                        <strong>平均置信度:</strong> ${(avgConfidence * 100).toFixed(1)}%
                    </div>
                    <div class="col-md-3">
                        <strong>总批次数:</strong> ${results.length}
                    </div>
                    <div class="col-md-3">
                        <strong>估算等级:</strong> ${getAverageLevel(results)}
                    </div>
                </div>
            </div>
        </div>`;
        
        // 添加详细分析信息（如果有的话）
        if (results.length > 0 && results[0].analysis) {
            html += generateAnalysisSummary(results);
        }
        
        $('#resultContent').html(html);
        $('#batchResult').show();
    }
    
    function getAverageLevel(results) {
        // 根据平均词汇量确定等级
        const avgEstimate = results.reduce((sum, r) => sum + r.estimate, 0) / results.length;
        
        if (avgEstimate < 3000) return '小学水平';
        if (avgEstimate < 6000) return '初中水平';
        if (avgEstimate < 12000) return '高中水平';
        if (avgEstimate < 18000) return '四级水平';
        if (avgEstimate < 25000) return '六级水平';
        return '高级水平';
    }
    
    function generateAnalysisSummary(results) {
        // 计算平均分析数据
        const avgAnalysis = {
            total_words: 0,
            known_words: 0,
            unknown_words: 0,
            accuracy: 0,
            avg_word_length: 0,
            avg_frequency_rank: 0,
            rare_words_ratio: 0,
            academic_ratio: 0,
            complexity_score: 0
        };
        
        let validResults = results.filter(r => r.analysis);
        if (validResults.length === 0) return '';
        
        validResults.forEach(result => {
            avgAnalysis.total_words += result.analysis.total_words;
            avgAnalysis.known_words += result.analysis.known_words;
            avgAnalysis.unknown_words += result.analysis.unknown_words;
            avgAnalysis.accuracy += result.analysis.accuracy;
            avgAnalysis.avg_word_length += result.analysis.avg_word_length;
            avgAnalysis.avg_frequency_rank += result.analysis.avg_frequency_rank;
            avgAnalysis.rare_words_ratio += result.analysis.rare_words_ratio;
            avgAnalysis.academic_ratio += result.analysis.academic_ratio;
            avgAnalysis.complexity_score += result.analysis.complexity_score;
        });
        
        const count = validResults.length;
        Object.keys(avgAnalysis).forEach(key => {
            avgAnalysis[key] = avgAnalysis[key] / count;
        });
        
        return `
            <div class="card mt-3">
                <div class="card-body">
                    <h6><i class="fas fa-chart-bar me-2"></i>详细分析汇总</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-muted">测试统计</h6>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均总单词数:</span>
                                <span class="fw-bold">${Math.round(avgAnalysis.total_words)}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均认识单词:</span>
                                <span class="fw-bold text-success">${Math.round(avgAnalysis.known_words)}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均不认识单词:</span>
                                <span class="fw-bold text-danger">${Math.round(avgAnalysis.unknown_words)}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均准确率:</span>
                                <span class="fw-bold text-primary">${(avgAnalysis.accuracy * 100).toFixed(1)}%</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-muted">词汇特征</h6>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均词长:</span>
                                <span class="fw-bold">${avgAnalysis.avg_word_length.toFixed(2)}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>平均词频排名:</span>
                                <span class="fw-bold">${Math.round(avgAnalysis.avg_frequency_rank).toLocaleString()}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>稀有词汇比例:</span>
                                <span class="fw-bold">${(avgAnalysis.rare_words_ratio * 100).toFixed(1)}%</span>
                            </div>
                            <div class="d-flex justify-content-between mb-1">
                                <span>学术词汇比例:</span>
                                <span class="fw-bold">${(avgAnalysis.academic_ratio * 100).toFixed(1)}%</span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-3">
                        <h6 class="text-muted">复杂度分析</h6>
                        <div class="d-flex justify-content-between">
                            <span>综合复杂度得分:</span>
                            <span class="fw-bold text-warning">${avgAnalysis.complexity_score.toFixed(3)}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    function showAlert(message, type) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('#alertContainer').html(alertHtml);
    }
});
</script>
{% endblock %} 